const fs = require('fs');
const path = require('path');

/**
 * 生成构建时间文件
 * 在每次构建时创建包含当前时间的文件，供页面使用
 */
function generateBuildTime() {
  const now = new Date();
  const buildTime = now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });

  const buildTimeData = {
    buildTime,
    timestamp: now.getTime(),
    date: now.toISOString()
  };

  // 确保目录存在
  const outputDir = path.join(__dirname, '..', 'src', 'utils');
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  // 写入构建时间文件
  const outputPath = path.join(outputDir, 'build-time.ts');
  const content = `// 此文件由构建脚本自动生成，请勿手动修改
export interface BuildTimeData {
  buildTime: string;
  timestamp: number;
  date: string;
}

export const BUILD_TIME: BuildTimeData = ${JSON.stringify(buildTimeData, null, 2)};
`;

  fs.writeFileSync(outputPath, content, 'utf8');
  console.log(`✅ 构建时间已生成: ${buildTime}`);
}

// 如果直接运行此脚本
if (require.main === module) {
  generateBuildTime();
}

module.exports = generateBuildTime;
